package com.kekezu.kppw.data;

import android.content.Context;
import android.text.Html;
import android.widget.Toast;

import com.kekezu.kppw.bean.UserBean;
import com.kekezu.kppw.utils.ConfigInc;
import com.kekezu.kppw.utils.HttpUtils;

import net.tsz.afinal.FinalDb;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChatData {
	static FinalDb db;

	/**
	 * 系统消息
	 * 
	 * @param page
	 * @param messageType
	 * @param context
	 * @return
	 */
	public static ArrayList<HashMap<String, Object>> getMessageList(int page,
			String messageType, Context context) {
		ArrayList<HashMap<String, Object>> taskList = new ArrayList<HashMap<String, Object>>();
		String urlString = ConfigInc.getServiceAdress(context)
				+ "user/messageList?";
		HttpUtils httpUtils = HttpUtils.getInstance();

		Map<String, String> params = new HashMap<String, String>();

		db = ConfigInc.getCreateDB(context);
		List<UserBean> users = db.findAll(UserBean.class);
		params.put("token", "" + users.get(0).getToken());
		params.put("page", "" + page);
		params.put("messageType", messageType);

		try {
			String strJson = httpUtils.httpGet(urlString, params, context);
			JSONObject jsonObject = new JSONObject(strJson);
			String resCode = jsonObject.getString("code");

			// 对返回的数据进行判断
			if (resCode.equals("1000")) {
				JSONObject jsondata = new JSONObject(
						jsonObject.getString("data"));

				JSONObject jsonmessage = new JSONObject(
						jsondata.getString("message_list"));

				JSONArray jsonArray = jsonmessage.getJSONArray("data");

				if (jsonArray.length() > 0) {
					for (int i = 0; i < jsonArray.length(); i++) {
						HashMap<String, Object> map = new HashMap<String, Object>();
						JSONObject itemJsonObject = jsonArray.optJSONObject(i);

						map.put("id", itemJsonObject.getString("id"));
						map.put("message_title",
								itemJsonObject.getString("message_title"));
						map.put("message_content", Html.fromHtml(itemJsonObject
								.getString("message_content")));
						map.put("message_type",
								itemJsonObject.getString("message_type"));
						map.put("receive_time",
								itemJsonObject.getString("receive_time")
										.subSequence(0, 10));
						map.put("status", itemJsonObject.getString("status"));

						taskList.add(map);
					}
				}
			} else {
				Toast.makeText(context, jsonObject.getString("message"),
						Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return taskList;
	}

}
